package com.ruoyi.hr.controller.hr;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.hr.domain.Authority;
import com.ruoyi.hr.domain.Companys;
import com.ruoyi.hr.domain.CompanysRegister;
import com.ruoyi.hr.service.AuthorityService;
import com.ruoyi.hr.service.CompAdminService;
import com.ruoyi.hr.service.CompanysService;
import com.ruoyi.hr.service.SkyMsgAlarmService;
import com.ruoyi.hr.service.welfare.welfareRegion.WelfareTypeService;
import com.ruoyi.system.domain.SysUser;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 公司管理控制层
 */
@Controller
@RequestMapping("/company/admin")
public class CompAdminController extends BaseController {

    @Autowired
    private CompAdminService compAdminService;

    @Autowired
    private CompanysService companysService;

    @Autowired
    AuthorityService authorityService;

    @Autowired
    private WelfareTypeService welfareTypeService;

    @Autowired
    SkyMsgAlarmService skyMsgAlarmService;

    private String prefix = "hr/companyAdmin";

    /**
     * 跳转新增页面
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/companyAdmin";
    }

    /**
     * 新增登记公司跳转
     */
    @RequiresPermissions("hr:compAdmin:add")
    @GetMapping("/add/register")
    public String add(ModelMap mmap) {
        List<Companys> companys = companysService.findAllCompanys(null);
        mmap.put("companys", companys);
        return prefix + "/addRegister";
    }

    /**
     * 根据权限及条件查询公司登记表数据
     *
     * @param companysRegister
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CompanysRegister companysRegister) {
        SysUser user = ShiroUtils.getSysUser();
        List<Authority> authorityList = authorityService.getAuthorityUser(user.getUserId().toString());
        int isAdmin = 0;
        if (authorityList.size() == 1) {
            if (authorityList.get(0).getIsAdmin() != null) {
                isAdmin = 1;
            }
        }
        List<CompanysRegister> companysList = compAdminService.getCompanysRegister(companysRegister, authorityList, isAdmin);
        //因为不在同一个数据源，需要单独写操作MySql库的方法
        for (CompanysRegister companysRegister1 : companysList) {
            companysRegister1.setRegByName(compAdminService.getRegByName(companysRegister1.getRegBy()));
        }
        return getDataTable(companysList);
    }


    /**
     * 新增登记公司
     *
     * @param companysRegister
     * @return
     */
    @PostMapping("/add/register")
    @ResponseBody
    public AjaxResult addSaveRegister(@Validated CompanysRegister companysRegister) {
        companysRegister.setRegBy(ShiroUtils.getSysUser().getUserId().intValue());
        return toAjax(compAdminService.insertCompanysRegister(companysRegister));
    }

    /**
     * (确认检查,取消确认,执行新增)
     */
    @PostMapping("/ProcedureRegister")
    @ResponseBody
    public String procedureRegister(CompanysRegister companysRegister, String procedure) {
        SysUser user = ShiroUtils.getSysUser();
        List<Authority> authorityList = authorityService.getAuthorityUser(user.getUserId().toString());
        List<CompanysRegister> companysList = compAdminService.getCompanysRegisterByProcedure(companysRegister, authorityList);
        String sql;//存储过程语句
        String msg;//异常信息
        String msgAdd = "";//叠加异常信息
        //外list是结果集数量，里list是每个结果集返回的记录数
        List<List<Map<String, Object>>> list;
        for (CompanysRegister companysRegister1 : companysList) {
            //拼串存储过程语句
            sql = "declare @RetVal varchar(50) exec " + procedure + " " + companysRegister1.getId() + "," + ShiroUtils.getSysUser().getUserId() + ",@RetVal output select @RetVal";
            //执行存储过程,返回一个Map,键为空
            list = compAdminService.executeProcedure(sql);
            //todo 循环叠加list提示
            if (list.size() > 1) {
                for (List<Map<String, Object>> list1 : list) {
                    if (list1.size() > 0) {
                        msg = skyMsgAlarmService.getMsgById(list1.get(0).get("").toString());
                        if (msg != null) {
                            msgAdd += msg + " 公司名称:" + companysRegister1.getTitle() + "\n";
                        }
                    }
                }
            } else {
                String mgsId = list.toString();
                msg = skyMsgAlarmService.getMsgById(mgsId.substring(3, mgsId.length() - 2));
                if (msg != null) {
                    msgAdd += msg + " 公司名称:" + companysRegister1.getTitle() + "\n";
                }
            }
        }
        return msgAdd;
    }

    /**
     * 修改登记公司跳转
     */
    @GetMapping("/editCompanysRegister")
    public String edit(int id, ModelMap mmap) {
        List<Companys> companys = companysService.findAllCompanys(null);
        mmap.put("companys", companys);
        CompanysRegister companysRegister = compAdminService.getCompanysRegisterById(id);
        mmap.put("companysRegister", companysRegister);
        return prefix + "/editRegister";
    }

    /**
     * 修改登记公司
     *
     * @param companysRegister
     * @return
     */
    @PostMapping("/edit/register")
    @ResponseBody
    public AjaxResult editSaveRegister(@Validated CompanysRegister companysRegister) {
        return toAjax(compAdminService.updateCompanysRegister(companysRegister));
    }

    /**
     * 删除登记公司
     *
     * @param ids
     * @return
     */
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(compAdminService.deleteCompanysRegister(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 跳转变更页面
     */
    @GetMapping("/change")
    public String change(ModelMap mmap) {
        return prefix + "/changeComp";
    }

    /**
     * 跳转选择变更公司窗口
     */
    @GetMapping("/selectCompany")
    public String selectCompany(ModelMap mmap, String type) {
        Authority authority = authorityService.findAuthorAndIsAdmin();
        startPage();
        List<Companys> companysList = companysService.findAllByAuthority(new Companys(),authority);
        mmap.put("companysList", companysList);
        mmap.put("type", type);
        return prefix + "/selectCompany";
    }

    /**
     * 新增变更,失效公司
     */
    @PostMapping("/addComp")
    @ResponseBody
    public AjaxResult addComp(String ids, String type) {
        String[] arry = ids.split(",");
        String sql;
        for (String id : arry) {
            sql = "oSP_CompAdd " + id + "," + type + "," + ShiroUtils.getSysUser().getUserId() + ",0";
            compAdminService.executeProcedure(sql);
        }
        return toAjax(1);
    }

    /**
     * 修改公司跳转
     */
    @GetMapping("/editCompanys")
    public String editCompanys(int id, ModelMap mmap) {
        List<Companys> companys = companysService.findAllCompanys(null);
        mmap.put("companys", companys);
        CompanysRegister companysRegister = compAdminService.getCompanysRegisterById(id);
        mmap.put("companysRegister", companysRegister);
        return prefix + "/editComp";
    }

    /**
     * 跳转变更页面
     */
    @GetMapping("/invalid")
    public String invalid(ModelMap mmap) {
        return prefix + "/invalidComp";
    }

    /**
     * 修改登记公司跳转
     */
    @GetMapping("/expirationDate")
    public String expirationDate(String id, ModelMap mmap) {
        List<CompanysRegister> companysRegisters = compAdminService.getCompanysRegisterByIds(id);
        mmap.put("companysRegisters", companysRegisters);
        return prefix + "/invalidDate";
    }

    /**
     * 修改失效日期
     *
     * @param ids
     * @param effectDate
     * @return
     */
    @PostMapping("/editInvalidDate")
    @ResponseBody
    public AjaxResult editInvalidDate(@Validated String ids, String effectDate) {
        return toAjax(compAdminService.updateInvalidDate(ids, effectDate));
    }

    /**
     * 公司管理历史跳转
     */
    @GetMapping("/history")
    public String history(ModelMap mmap) {
        return prefix + "/historyComp";
    }

    /**
     * 根据起始和结束时间查找历史操作数据
     *
     * @param startDate 起始时间
     * @param endDate   结束时间
     * @return 历史操作数据
     */
    @PostMapping("/historyList")
    @ResponseBody
    public TableDataInfo historyList(String startDate, String endDate) {
        SysUser user = ShiroUtils.getSysUser();
        List<Authority> authorityList = authorityService.getAuthorityUser(user.getUserId().toString());
        int isAdmin = 0;
        if (authorityList.size() == 1) {
            if (authorityList.get(0).getIsAdmin() != null) {
                isAdmin = 1;
            }
        }
        startPage();
        List<CompanysRegister> companysList = compAdminService.getCompanysRegisterByDate(startDate, endDate, authorityList, isAdmin);
        return getDataTable(companysList);
    }
}
